<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑预案' : '新增预案'"
    width="900px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="plan-form"
    >
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="预案名称" prop="planName">
                <el-input v-model="form.planName" placeholder="请输入预案名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预案类型" prop="planType">
                <el-select v-model="form.planType" placeholder="请选择预案类型" style="width: 100%">
                  <el-option label="防洪预案" value="flood_control" />
                  <el-option label="抗旱预案" value="drought_control" />
                  <el-option label="应急预案" value="emergency" />
                  <el-option label="维护预案" value="maintenance" />
                  <el-option label="安全预案" value="safety" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="版本号" prop="version">
                <el-input v-model="form.version" placeholder="如：v1.0" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先级" prop="priority">
                <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
                  <el-option label="低" value="low" />
                  <el-option label="中" value="medium" />
                  <el-option label="高" value="high" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="预案状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                  <el-option label="草稿" value="draft" />
                  <el-option label="审核中" value="reviewing" />
                  <el-option label="生效" value="active" />
                  <el-option label="已废止" value="obsolete" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="适用范围" prop="scope">
                <el-select v-model="form.scope" placeholder="请选择适用范围" style="width: 100%">
                  <el-option label="全库区" value="全库区" />
                  <el-option label="主坝区域" value="主坝区域" />
                  <el-option label="副坝区域" value="副坝区域" />
                  <el-option label="溢洪道" value="溢洪道" />
                  <el-option label="进水口" value="进水口" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="生效时间" prop="effectiveTime">
                <el-date-picker
                  v-model="form.effectiveTime"
                  type="datetime"
                  placeholder="选择生效时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="失效时间" prop="expireTime">
                <el-date-picker
                  v-model="form.expireTime"
                  type="datetime"
                  placeholder="选择失效时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="预案描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入预案描述"
            />
          </el-form-item>
        </el-tab-pane>

        <!-- 触发条件 -->
        <el-tab-pane label="触发条件" name="trigger">
          <div class="trigger-conditions">
            <div class="condition-header">
              <h4>触发条件设置</h4>
              <el-button type="primary" size="small" @click="addCondition">
                <el-icon><Plus /></el-icon>
                添加条件
              </el-button>
            </div>
            
            <div v-if="form.triggerConditions.length === 0" class="empty-conditions">
              <el-empty description="暂无触发条件，请点击添加条件" />
            </div>
            
            <div v-for="(condition, index) in form.triggerConditions" :key="index" class="condition-item">
              <el-card shadow="never">
                <template #header>
                  <div class="condition-header">
                    <span>条件 {{ index + 1 }}</span>
                    <el-button type="danger" size="small" @click="removeCondition(index)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </div>
                </template>
                
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="监测参数">
                      <el-select v-model="condition.parameter" placeholder="请选择参数" style="width: 100%">
                        <el-option label="水位" value="water_level" />
                        <el-option label="流量" value="flow" />
                        <el-option label="降雨量" value="rainfall" />
                        <el-option label="库容" value="capacity" />
                        <el-option label="水质" value="water_quality" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="条件操作符">
                      <el-select v-model="condition.operator" placeholder="请选择操作符" style="width: 100%">
                        <el-option label="大于" value=">" />
                        <el-option label="大于等于" value=">=" />
                        <el-option label="小于" value="<" />
                        <el-option label="小于等于" value="<=" />
                        <el-option label="等于" value="=" />
                        <el-option label="不等于" value="!=" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="阈值">
                      <el-input v-model="condition.value" placeholder="请输入阈值" type="number" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="持续时间">
                      <el-input-number v-model="condition.duration" :min="0" placeholder="分钟" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="逻辑关系">
                      <el-select v-model="condition.logic" placeholder="请选择逻辑关系" style="width: 100%">
                        <el-option label="且(AND)" value="AND" />
                        <el-option label="或(OR)" value="OR" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-card>
            </div>
          </div>
        </el-tab-pane>

        <!-- 执行步骤 -->
        <el-tab-pane label="执行步骤" name="steps">
          <div class="execution-steps">
            <div class="steps-header">
              <h4>执行步骤</h4>
              <el-button type="primary" size="small" @click="addStep">
                <el-icon><Plus /></el-icon>
                添加步骤
              </el-button>
            </div>
            
            <div v-if="form.executionSteps.length === 0" class="empty-steps">
              <el-empty description="暂无执行步骤，请点击添加步骤" />
            </div>
            
            <div v-for="(step, index) in form.executionSteps" :key="index" class="step-item">
              <el-card shadow="never">
                <template #header>
                  <div class="step-header">
                    <span>步骤 {{ index + 1 }}</span>
                    <div class="step-actions">
                      <el-button type="primary" size="small" @click="moveStepUp(index)" :disabled="index === 0">
                        <el-icon><ArrowUp /></el-icon>
                      </el-button>
                      <el-button type="primary" size="small" @click="moveStepDown(index)" :disabled="index === form.executionSteps.length - 1">
                        <el-icon><ArrowDown /></el-icon>
                      </el-button>
                      <el-button type="danger" size="small" @click="removeStep(index)">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                  </div>
                </template>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="步骤名称">
                      <el-input v-model="step.name" placeholder="请输入步骤名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="执行类型">
                      <el-select v-model="step.type" placeholder="请选择执行类型" style="width: 100%">
                        <el-option label="人工操作" value="manual" />
                        <el-option label="自动执行" value="auto" />
                        <el-option label="系统通知" value="notification" />
                        <el-option label="设备控制" value="device_control" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="责任人">
                      <el-select v-model="step.responsible" placeholder="请选择责任人" style="width: 100%">
                        <el-option label="值班员" value="duty_officer" />
                        <el-option label="技术员" value="technician" />
                        <el-option label="主管" value="supervisor" />
                        <el-option label="系统管理员" value="admin" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="预计耗时">
                      <el-input-number v-model="step.estimatedTime" :min="0" placeholder="分钟" style="width: 100%" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-form-item label="步骤描述">
                  <el-input
                    v-model="step.description"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入步骤详细描述"
                  />
                </el-form-item>
                
                <el-form-item label="注意事项">
                  <el-input
                    v-model="step.notes"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入注意事项"
                  />
                </el-form-item>
              </el-card>
            </div>
          </div>
        </el-tab-pane>

        <!-- 相关人员 -->
        <el-tab-pane label="相关人员" name="personnel">
          <div class="personnel-section">
            <h4>通知人员</h4>
            <el-transfer
              v-model="form.notificationPersonnel"
              :data="availablePersonnel"
              :titles="['可选人员', '通知人员']"
              :button-texts="['移除', '添加']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
            />
          </div>
          
          <div class="personnel-section">
            <h4>执行人员</h4>
            <el-transfer
              v-model="form.executionPersonnel"
              :data="availablePersonnel"
              :titles="['可选人员', '执行人员']"
              :button-texts="['移除', '添加']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
              }"
            />
          </div>
        </el-tab-pane>

        <!-- 附件资料 -->
        <el-tab-pane label="附件资料" name="attachments">
          <div class="attachments-section">
            <el-upload
              v-model:file-list="form.attachments"
              class="upload-demo"
              drag
              multiple
              :auto-upload="false"
              :on-change="handleFileChange"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持 jpg/png/gif/pdf/doc/docx/xls/xlsx 文件，且不超过 10MB
                </div>
              </template>
            </el-upload>
            
            <div v-if="form.attachments.length > 0" class="attachment-list">
              <h4>已上传文件</h4>
              <el-table :data="form.attachments" stripe>
                <el-table-column prop="name" label="文件名" />
                <el-table-column prop="size" label="文件大小" width="120">
                  <template #default="{ row }">
                    {{ formatFileSize(row.size) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="{ row, $index }">
                    <el-button type="danger" size="small" @click="removeAttachment($index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saveLoading">
          <el-icon><Check /></el-icon>
          保存
        </el-button>
        <el-button type="success" @click="handleTest" v-if="isEdit">
          <el-icon><VideoPlay /></el-icon>
          测试预案
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Plus,
  Delete,
  ArrowUp,
  ArrowDown,
  Check,
  VideoPlay,
  UploadFilled
} from '@element-plus/icons-vue'

interface Props {
  visible: boolean
  formData?: any
  isEdit?: boolean
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  formData: () => ({}),
  isEdit: false
})

const emit = defineEmits<Emits>()

const formRef = ref()
const activeTab = ref('basic')
const saveLoading = ref(false)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单数据
const form = reactive({
  planName: '',
  planType: '',
  version: '',
  priority: '',
  status: 'draft',
  scope: '',
  effectiveTime: null,
  expireTime: null,
  description: '',
  triggerConditions: [],
  executionSteps: [],
  notificationPersonnel: [],
  executionPersonnel: [],
  attachments: []
})

// 可选人员列表
const availablePersonnel = ref([
  { key: 1, label: '张三 - 值班员', disabled: false },
  { key: 2, label: '李四 - 技术员', disabled: false },
  { key: 3, label: '王五 - 主管', disabled: false },
  { key: 4, label: '赵六 - 系统管理员', disabled: false },
  { key: 5, label: '孙七 - 安全员', disabled: false }
])

// 表单验证规则
const rules = {
  planName: [
    { required: true, message: '请输入预案名称', trigger: 'blur' }
  ],
  planType: [
    { required: true, message: '请选择预案类型', trigger: 'change' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择预案状态', trigger: 'change' }
  ]
}

// 添加触发条件
const addCondition = () => {
  form.triggerConditions.push({
    parameter: '',
    operator: '',
    value: '',
    duration: 0,
    logic: 'AND'
  })
}

// 删除触发条件
const removeCondition = (index: number) => {
  form.triggerConditions.splice(index, 1)
}

// 添加执行步骤
const addStep = () => {
  form.executionSteps.push({
    name: '',
    type: '',
    responsible: '',
    estimatedTime: 0,
    description: '',
    notes: ''
  })
}

// 删除执行步骤
const removeStep = (index: number) => {
  form.executionSteps.splice(index, 1)
}

// 上移步骤
const moveStepUp = (index: number) => {
  if (index > 0) {
    const temp = form.executionSteps[index]
    form.executionSteps[index] = form.executionSteps[index - 1]
    form.executionSteps[index - 1] = temp
  }
}

// 下移步骤
const moveStepDown = (index: number) => {
  if (index < form.executionSteps.length - 1) {
    const temp = form.executionSteps[index]
    form.executionSteps[index] = form.executionSteps[index + 1]
    form.executionSteps[index + 1] = temp
  }
}

// 文件变化处理
const handleFileChange = (file: any, fileList: any[]) => {
  form.attachments = fileList
}

// 删除附件
const removeAttachment = (index: number) => {
  form.attachments.splice(index, 1)
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(1) + ' MB'
  }
}

// 保存
const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    saveLoading.value = true
    
    // 模拟保存API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(props.isEdit ? '预案更新成功' : '预案创建成功')
    emit('success')
  } catch (error) {
    ElMessage.error('表单验证失败')
  } finally {
    saveLoading.value = false
  }
}

// 测试预案
const handleTest = () => {
  ElMessage.info('预案测试功能开发中...')
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 重置表单
const resetForm = () => {
  Object.keys(form).forEach(key => {
    if (Array.isArray(form[key])) {
      form[key] = []
    } else {
      form[key] = ''
    }
  })
  form.status = 'draft'
  activeTab.value = 'basic'
}

// 监听表单数据变化
watch(() => props.formData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    Object.assign(form, {
      ...newData,
      triggerConditions: newData.triggerConditions || [],
      executionSteps: newData.executionSteps || [],
      notificationPersonnel: newData.notificationPersonnel || [],
      executionPersonnel: newData.executionPersonnel || [],
      attachments: newData.attachments || []
    })
  } else {
    resetForm()
  }
}, { immediate: true })

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (!visible) {
    formRef.value?.clearValidate()
  }
})
</script>

<style scoped>
.plan-form {
  max-height: 60vh;
  overflow-y: auto;
}

.trigger-conditions,
.execution-steps {
  margin-top: 10px;
}

.condition-header,
.steps-header,
.step-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.condition-item,
.step-item {
  margin-bottom: 15px;
}

.step-actions {
  display: flex;
  gap: 5px;
}

.empty-conditions,
.empty-steps {
  text-align: center;
  padding: 40px 0;
}

.personnel-section {
  margin-bottom: 30px;
}

.personnel-section h4 {
  margin-bottom: 15px;
  color: #333;
}

.attachments-section {
  padding: 20px 0;
}

.attachment-list {
  margin-top: 20px;
}

.attachment-list h4 {
  margin-bottom: 15px;
  color: #333;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-tabs--border-card) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.el-tab-pane) {
  padding: 20px;
}

:deep(.el-transfer) {
  display: flex;
  justify-content: center;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  background-color: #f8f9fa;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>